<?php

/**
 */

namespace App\Api\CatchOrder;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class DouYinNew
{
    protected $log;
    protected $root;
    protected $config;
    protected $url;
    // public $shop_id = '27718348';
    public $shop_id = '';
    public $shop_name = '';
    public $app_key = '';
    public $app_secret = '';
    public $tokenNums = 0;
    public function __construct($shop_id, $app_key, $app_secret)
    {
        // $this->config = config('DouYin');
        $this->log = new Logger('DouYinNew');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/DouYinNew.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );

        $this->root = new Logger('DouYinNewRootLog');
        $this->root->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/DouYinNewRootLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->shop_id = $shop_id;
        $this->app_key = $app_key;
        $this->app_secret = $app_secret;
        $this->tokenNums = 1;
    }


    /**
     * @desc 发货地址更新
     * @return boolean
     */
    public function async($data = array())
    {
        $method = 'order.logisticsAdd';
        $code = 'jd';
        if (!empty($data['express_company']) && $data['express_company'] == 'EMS') {
            $code = 'ems';
        } else if (!empty($data['express_company']) && strstr($data['express_company'], '顺丰')) {
            $code = 'shunfeng';
        } elseif (!empty($data['express_company']) && strstr($data['express_company'], 'EMS')) {
            $code = 'ems';
        } elseif (!empty($data['express_company']) && strstr($data['express_company'], '邮政')) {
            $code = 'ems';
        }
        $datas = [
            'company' => $data['express_company'],
            'company_code' => $code, //物流code
            'logistics_code' => $data['express_number'], // 快递单号
            'order_id' => $data['dist_orderno'],
        ];

        // if (!empty($data['express_company']) && !empty($data['express_number']) && ) {
        //     $datas['company'] = $data['express_company'];
        //     $datas['company_code'] = $code;
        //     $datas['logistics_code'] = $data['express_number'];
        // }
        if ($data['express_company'] == '无需物流' || $data['express_company'] == '营业厅上门开卡') {
            $datas = [
                'company_code' => 'qita',
                'order_id' => $data['dist_orderno'],
            ];
        }

        // var_dump($data);
        // die();
        $res = $this->send($method, $datas);
        $this->root->info('参数:' . json_encode($datas) . '返回结果' . json_encode($res));
        return $res;
    }
    /**
     * 订单解密
     */
    public function batchDecrypt($datas = array(), $nums = 1)
    {
        $method = 'order.batchDecrypt';
        // $data = [
        //     'cipher_infos' => [
        //         [
        //             'auth_id' => '4888989959149253925',
        //             'cipher_text' => '$uEE5r4ZfYtg3CVe/cL0vhctdBanavEWCheknfLRSVEA=$bZiYXeeEK3sdaFjCqCLHKz47gj2UNQNjm18YRpixiysxC9ck1EWIITI/g8nB4NmhTysv3Hi7NYci8gBXUuP1QNkuJGdiYSZrxCYjcR4e+DDX*CgkIARCtHCABKAESPgo8Cku/9MKMNJrOCZCOq+fDIWZE1DsZ1IOccW+TsD8GIXGngUyAdacsXhPZN70rSa7GyBCsuFfiPQMz/WweGgA=$1$$'
        //         ],
        //     ]
        // ];
        $data = [
            'cipher_infos' => $datas
        ];
        $res = $this->send($method, $data);
        $arr = [];
        if (!empty($res)) {
            $obj = json_decode($res, true);
            if ($obj['code'] == 10000) {
                $arr = $obj['data'];
            }
        }
        if (empty($arr) && $nums == 1) {
            return $this->batchDecrypt($datas, 2);
        }
        return $arr;
    }

    function getAcToken()
    {
        $token = Cache::get('order_douyin_accesstoken' . $this->shop_id);
        $this->root->info('获取token---' . json_encode($token));
        if ($token) {
            $tokenArr = json_decode($token, true);
            if ($tokenArr['time'] > time()) {
                $token = !empty($tokenArr['data']['access_token']) ? $tokenArr['data']['access_token'] : '';
                return $token;
            }
            if ((time() - $tokenArr['time']) > (3 * 24 * 60 * 60)) {
                Cache::forever('order_douyin_accesstoken' . $this->shop_id, '');
            }
            // 当过期之后 刷新
            $method = 'token.refresh';
            $data = [
                'refresh_token' => $tokenArr['data']['refresh_token'],
                'grant_type'  => 'refresh_token'
            ];
            $res = $this->send($method, $data);
        } else {
            $method = 'token.create';
            $data = [
                'grant_type' => 'authorization_self',
                'shop_id'   => $this->shop_id,
                'code'      => '', // 82bdc687-eff1-4f63-8444-0b43086c25fd
            ];
            $res = $this->send($method, $data);
            // var_dump($res, 1111111);
            $this->root->info('获取创建token---' . $res);
        }
        if (!empty($res)) {
            $tokenArr = json_decode($res, true);
            if (!empty($tokenArr['code']) && $tokenArr['code'] == 40003) {
                Cache::forever('order_douyin_accesstoken' . $this->shop_id, '');

                if ($this->tokenNums > 5) {
                    return false;
                }
                $this->tokenNums++;
                return $this->getAcToken();
            }
            if (empty($tokenArr['code']) || $tokenArr['code'] != 10000) {
                $this->root->info('获取token失败---' . $res);
                return false;
            }

            $token = !empty($tokenArr['data']['access_token']) ? $tokenArr['data']['access_token'] : '';
            if (empty($token)) {
                $this->root->info('获取token失败---' . $res);
                return false;
            }
            $time2 = time() + $tokenArr['data']['expires_in'];
            $tokenArr['time'] = $time2;
            Cache::forever('order_douyin_accesstoken' . $this->shop_id, json_encode($tokenArr));
            return $token;
        }
        return false;
    }
    // 获取订单表   不使用
    public function orderList($page = 0, $creatTime = '', $endTime = '')
    {
        $method = 'order.searchList';
        $data = [
            'page' => $page,
            'size' => 10,
            'create_time_start' => !empty($creatTime) ? $creatTime : time() - (60 * 2),
            'create_time_end'  => !empty($endTime) ? $endTime : time(),
            // 'order_status' => '2'
        ];
        $res = $this->send($method, $data);
        $arr = json_decode($res, true);
        if (!empty($arr['data']['total'])) {
            if ($page * 10 >= $arr['data']['total']) {
                $page = 0;
            } else {
                $page++;
            }
        }
        if (!empty($arr['data']['shop_order_list'])) {
            $decryData = [];
            $paramsabc  = [];
            foreach ($arr['data']['shop_order_list'] as $key => &$v) {
                if (empty($v['order_status']) || ($v['order_status'] != 2 && $v['order_status'] != 105)) {
                    // continue;
                }
                // $res = DB::table('flow_dd_no_submit_order')->where(['order_num' => $v['order_id']])->first();
                // if ($res) {
                //     continue;
                // }
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['encrypt_post_receiver'], //收件人姓名
                ];
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['encrypt_post_tel']  // 收件人电话
                ];
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['post_addr']['encrypt_detail']  // 收件人详细地址
                ];
                if (!empty($v['user_id_info']['encrypt_id_card_no'])) {
                    $decryData[] = [
                        'auth_id' =>  $v['order_id'],
                        'cipher_text' => $v['user_id_info']['encrypt_id_card_no']  // 证件号
                    ];
                }
                if (!empty($v['user_id_info']['encrypt_id_card_name'])) {
                    $decryData[] = [
                        'auth_id' =>  $v['order_id'],
                        'cipher_text' => $v['user_id_info']['encrypt_id_card_name']  // 证件姓名
                    ];
                }
                $status = 1;
                if (!empty($v['post_addr']['city']) && !empty($v['post_addr']['province'])) {
                    // if (!empty($v['sku_order_list'][0]['spec'][0]['value']) && $v['sku_order_list'][0]['code'] == '星卡流量版（59元）-省公司-宇轩') {
                    //     $status = 2;
                    // }
                    // $agen_id = '1';
                    // $dept_str = '1.';
                    // if (!empty($v['sku_order_list'][0]['author_id'])) {
                    //     $resUser = DB::table('flow_user')->where([['remark', 'like', '%' . $v['sku_order_list'][0]['author_id'] . ',%']])->orWhere([['remark', 'like', '%,' . $v['sku_order_list'][0]['author_id'] . '%']])->first();
                    //     if (!empty($resUser)) {
                    //         $agen_id = $resUser->id;
                    //         $dept_str = $resUser->dept_str;
                    //     }
                    // }

                    $paramsabc[] = [
                        'user_name' => !empty($v['user_id_info']['encrypt_id_card_name']) ? $v['user_id_info']['encrypt_id_card_name'] : $v['encrypt_post_receiver'],
                        'card_num' => !empty($v['user_id_info']['encrypt_id_card_no']) ? $v['user_id_info']['encrypt_id_card_no'] : '',
                        'user_phone'  => $v['encrypt_post_tel'],
                        'order_num' => !empty($v['order_id']) ? $v['order_id'] : 'SN_' . date('YmdHis', time()) . rand(1000, 9999),
                        'province' => $v['post_addr']['province']['name'],
                        'city'    => $v['post_addr']['city']['name'],
                        'area'  => $v['post_addr']['town']['name'],
                        'street' => !empty($v['post_addr']['street']['name']) ? $v['post_addr']['street']['name'] : '',
                        'addr' => $v['post_addr']['encrypt_detail'],
                        'author_id' => $v['sku_order_list'][0]['author_id'],
                        'author_name' => $v['sku_order_list'][0]['author_name'],
                        'c_biz_desc' => $v['sku_order_list'][0]['c_biz_desc'],
                        'product'  => $v['sku_order_list'][0]['code'],
                        'package_name' => $v['sku_order_list'][0]['spec'][0]['value'],
                        'status' => $status,
                        'created_at' => date('Y-m-d H:i:s', $v['create_time']),
                        'douyin_status_name' => $v['sku_order_list'][0]['main_status_desc'],
                        'shop_id' => $this->shop_id
                    ];
                }
            }
            $arr = [];
            $decyptArr = [];
            if (!empty($decryData)) {
                $decyptArr = $this->batchDecrypt($decryData);
            }

            if (!empty($paramsabc)) {
                foreach ($paramsabc as $key => &$v) {
                    $nums = 0;
                    if (empty($decyptArr['decrypt_infos'])) {
                        // $paramsabc = [];
                        break;
                    }
                    foreach ($decyptArr['decrypt_infos'] as $k => $val) {
                        if ($v['user_name'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['user_name'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['card_num'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['card_num'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['user_phone'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['user_phone'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['addr'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['addr'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($nums > 3) {
                            $nums = 0;
                            break;
                        }
                        //判断是否存入如果存在则修改 如果不存在则添加 添加的话需要 
                    }
                }
            }
        }
        //数据库 里面去重
        if (!empty($paramsabc)) {
            DB::table('dd_no_submit_order')->insert($paramsabc);
        }
        if ($page > 0 && $page < 5) {
            // $this->orderList($page, $creatTime, $endTime);
        }
        // 加入队列信息
        return 1;
    }
    // 弃用
    public function orderList_back($page = 0, $creatTime = '', $endTime = '')
    {
        $method = 'order.searchList';
        $data = [
            'page' => $page,
            'size' => 100,
            'create_time_start' => !empty($creatTime) ? $creatTime : time() - (60 * 2),
            'create_time_end'  => !empty($endTime) ? $endTime : time(),
            'order_status' => '2'
        ];
        $res = $this->send($method, $data);
        return $res;
        $arr = json_decode($res, true);
        // var_dump($arr);
        if (!empty($data['data']['total'])) {
            if ($page * 10 >= $data['data']['total']) {
                $page = 0;
            } else {
                $page++;
            }
        }
        if (!empty($arr['data']['shop_order_list'])) {
            $decryData = [];
            $paramsabc  = [];
            foreach ($arr['data']['shop_order_list'] as $key => &$v) {
                if (empty($v['order_status']) || $v['order_status'] != 2) {
                    continue;
                }
                // $res = DB::table('flow_dd_no_submit_order')->where(['order_num' => $v['order_id']])->first();
                // if ($res) {
                //     continue;
                // }
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['encrypt_post_receiver'], //收件人姓名
                ];
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['encrypt_post_tel']  // 收件人电话
                ];
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['post_addr']['encrypt_detail']  // 收件人详细地址
                ];
                if (!empty($v['user_id_info']['encrypt_id_card_no'])) {
                    $decryData[] = [
                        'auth_id' =>  $v['order_id'],
                        'cipher_text' => $v['user_id_info']['encrypt_id_card_no']  // 证件号
                    ];
                }
                if (!empty($v['user_id_info']['encrypt_id_card_name'])) {
                    $decryData[] = [
                        'auth_id' =>  $v['order_id'],
                        'cipher_text' => $v['user_id_info']['encrypt_id_card_name']  // 证件姓名
                    ];
                }
                $status = 1;
                if (!empty($v['post_addr']['city']) && !empty($v['post_addr']['province'])) {
                    if (!empty($v['sku_order_list'][0]['spec'][0]['value']) && $v['sku_order_list'][0]['code'] == '星卡流量版（59元）-省公司-宇轩') {
                        $status = 2;
                    }
                    $agen_id = '1';
                    $dept_str = '1.';
                    if (!empty($v['sku_order_list'][0]['author_id'])) {
                        $resUser = DB::table('flow_user')->where([['remark', 'like', '%' . $v['sku_order_list'][0]['author_id'] . ',%']])->orWhere([['remark', 'like', '%,' . $v['sku_order_list'][0]['author_id'] . '%']])->first();
                        if (!empty($resUser)) {
                            $agen_id = $resUser->id;
                            $dept_str = $resUser->dept_str;
                        }
                    }

                    $paramsabc[] = [
                        'user_name' => !empty($v['user_id_info']['encrypt_id_card_name']) ? $v['user_id_info']['encrypt_id_card_name'] : $v['encrypt_post_receiver'],
                        'card_num' => !empty($v['user_id_info']['encrypt_id_card_no']) ? $v['user_id_info']['encrypt_id_card_no'] : '',
                        'user_phone'  => $v['encrypt_post_tel'],
                        'order_num' => !empty($v['order_id']) ? $v['order_id'] : 'SN_' . date('YmdHis', time()) . rand(1000, 9999),
                        'province' => $v['post_addr']['province']['name'],
                        'city'    => $v['post_addr']['city']['name'],
                        'area'  => $v['post_addr']['town']['name'],
                        'street' => !empty($v['post_addr']['street']['name']) ? $v['post_addr']['street']['name'] : '',
                        'addr' => $v['post_addr']['encrypt_detail'],
                        'author_id' => $v['sku_order_list'][0]['author_id'],
                        'author_name' => $v['sku_order_list'][0]['author_name'],
                        'c_biz_desc' => $v['sku_order_list'][0]['c_biz_desc'],
                        'product'  => $v['sku_order_list'][0]['code'],
                        'package_name' => $v['sku_order_list'][0]['spec'][0]['value'],
                        'status' => $status,
                        'created_at' => date('Y-m-d H:i:s', $v['create_time']),
                        'douyin_status_name' => $v['sku_order_list'][0]['main_status_desc']
                    ];
                }
            }
            $arr = [];
            $decyptArr = [];
            if (!empty($decryData)) {
                $decyptArr = $this->batchDecrypt($decryData);
            }

            if (!empty($paramsabc)) {
                foreach ($paramsabc as $key => &$v) {
                    $nums = 0;
                    if (empty($decyptArr['decrypt_infos'])) {
                        // $paramsabc = [];
                        break;
                    }
                    foreach ($decyptArr['decrypt_infos'] as $k => $val) {
                        if ($v['user_name'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['user_name'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['card_num'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['card_num'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['user_phone'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['user_phone'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['addr'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['addr'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($nums > 3) {
                            $nums = 0;
                            break;
                        }
                    }
                    // $res = DB::table('flow_dd_no_submit_order') ->where(['order_num'=>$v['order_num']])->first();
                    // if($res){
                    //     unset($paramsabc[$key]);
                    // }
                }
            }
        }
        //数据库 里面去重
        if (!empty($paramsabc)) {
            DB::table('flow_dd_no_submit_order')->insert($paramsabc);
        }
        if ($page > 0) {
            $this->orderList($page);
        }
        return 1;
    }
    // 获取订单详情
    public function orderDetails($data = array())
    {

        $method = 'order.orderDetail';
        $data = [
            'shop_order_id' => $data['pid'],
        ];
        $res = $this->send($method, $data);
        if (!empty($res)) {
            $arr = json_decode($res, true);
        }
        $decryData = [];
        $paramsabc  = [];
        $isFlag = true;
        // 加密和解密 
        if (!empty($arr['data']['shop_order_detail'])) {

            $v = $arr['data']['shop_order_detail'];
            // 判断状态是否为 待发货的状态
            if (empty($v['order_status']) || ($v['order_status'] != 2 && $v['order_status'] != 105)) {
                // return []; // 如果订单状态 不为 2 的时候 返回空
                // return ['code' => 100, 'msg' => '已关闭订单'];
                $isFlag = false;
            }

            $decryData[] = [
                'auth_id' =>  $v['order_id'],
                'cipher_text' => $v['encrypt_post_receiver'], //收件人姓名
            ];
            $decryData[] = [
                'auth_id' =>  $v['order_id'],
                'cipher_text' => $v['encrypt_post_tel']  // 收件人电话
            ];
            $decryData[] = [
                'auth_id' =>  $v['order_id'],
                'cipher_text' => $v['post_addr']['encrypt_detail']  // 收件人详细地址
            ];
            if (!empty($v['user_id_info']['encrypt_id_card_no'])) {
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['user_id_info']['encrypt_id_card_no']  // 证件号
                ];
            }
            if (!empty($v['user_id_info']['encrypt_id_card_name'])) {
                $decryData[] = [
                    'auth_id' =>  $v['order_id'],
                    'cipher_text' => $v['user_id_info']['encrypt_id_card_name']  // 证件姓名
                ];
            }
            $status = 1;
            if (!empty($v['post_addr']['city']) && !empty($v['post_addr']['province'])) {
                $pageage_name = '';
                foreach($v['sku_order_list'] as $key_page => $vpage){
                    $pageage_name .= $vpage['product_name'].$vpage['spec'][0]['name'].'/'.$vpage['spec'][0]['value'];
                }
                $paramsabc[] = [
                    'user_name' => !empty($v['user_id_info']['encrypt_id_card_name']) ? $v['user_id_info']['encrypt_id_card_name'] : $v['encrypt_post_receiver'],
                    'card_num' => !empty($v['user_id_info']['encrypt_id_card_no']) ? $v['user_id_info']['encrypt_id_card_no'] : '',
                    'user_phone'  => $v['encrypt_post_tel'],
                    'order_num' => !empty($v['order_id']) ? $v['order_id'] : 'SN_' . date('YmdHis', time()) . rand(1000, 9999),
                    'province' => $v['post_addr']['province']['name'],
                    'city'    => $v['post_addr']['city']['name'],
                    'area'  => $v['post_addr']['town']['name'],
                    'street' => !empty($v['post_addr']['street']['name']) ? $v['post_addr']['street']['name'] : '',
                    'addr' => $v['post_addr']['encrypt_detail'],
                    'author_id' => $v['sku_order_list'][0]['author_id'],
                    'author_name' => $v['sku_order_list'][0]['author_name'],
                    'c_biz_desc' => $v['sku_order_list'][0]['c_biz_desc'],
                    'product'  => $v['sku_order_list'][0]['code'],
                    'package_name' => $pageage_name,
                    'status' => $status,
                    'dou_status' => $v['order_status'],
                    'created_at' => date('Y-m-d H:i:s', $v['create_time']),
                    'douyin_status_name' => $v['sku_order_list'][0]['main_status_desc'],
                    'money' => $v['order_amount']/100,
                    'seller_words' => $v['seller_words'],
                ];
                
            }

            $arr = [];
            $decyptArr = [];
            if (!empty($decryData) && $isFlag) {
                $decyptArr = $this->batchDecrypt($decryData);
            }

            if (!empty($paramsabc) && !empty($decyptArr)) {
                foreach ($paramsabc as $key => &$v) {
                    $nums = 0;

                    if (empty($decyptArr['decrypt_infos'])) {
                        // $paramsabc = [];
                        break;
                    }
                    foreach ($decyptArr['decrypt_infos'] as $k => $val) {
                        if (empty($val['decrypt_text'])) {
                            // $isFlag = false;
                        }
                        if ($v['user_name'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {

                            $v['user_name'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['card_num'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['card_num'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['user_phone'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['user_phone'] = $val['decrypt_text'];
                            $nums++;
                        }
                        if ($v['addr'] == $val['cipher_text'] && $v['order_num'] == $val['auth_id']) {
                            $v['addr'] = $val['decrypt_text'];
                            $nums++;
                        }
                    }
                }
            }
        }
        return ['code' => !empty($isFlag) ? 200 : 100, 'data' => $paramsabc];
        // if (!empty($isFlag)) {

        // }
        return [];
    }
    // 订单审核失败
    public function orderReview($array = array())
    {
        $method = 'order.review';
        $data = [
            'task_type' => 3001,
            'reject_code' => $array['status'],
            'object_id' => $array['orderno'],
        ];
        $return = $this->send($method, $data);
        $this->log->info('抖音订单审核参数:' . json_encode($data) . '返回结果:' . ($return));
        return $return;
    }
    // 订单
    // 物流信息 获取
    public function getCompany()
    {
        $method = 'order.logisticsCompanyList';
        $data = [];
        $res = $this->send($method, ['a' => 1]);
        $arr = json_decode($res, true);
        DB::table('flow_company_info')->insert($arr['data']);
        return 1;
    }
    public function sign($appKey, $appSecret, $method, $timestamp, $paramJson)
    {
        $paramPattern = 'app_key' . $appKey . 'method' . $method . 'param_json' . $paramJson . 'timestamp' . $timestamp . 'v2';

        $signPattern = $appSecret . $paramPattern . $appSecret;
        return hash_hmac("sha256", $signPattern, $appSecret);
    }
    public function marshal($param)
    {
        if ($param == null) {
            return "{}";
        }
        $param = $this->objToArray($param);
        $param = $this->rec_ksort($param); // 对关联数组中的kv，执行排序，需要递归
        $s = json_encode($param, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); // 重新序列化，确保所有key按字典序排序
        // 加入flag，确保斜杠不被escape，汉字不被escape
        return $s;
    }
    public function objToArray($data)
    {
        //先转成json string
        $jsonStr = json_encode($data);
        //再转成array
        return json_decode($jsonStr, true);
    }

    // 关联数组排序，递归
    public function rec_ksort($arr)
    {
        $kstring = true;
        foreach ($arr as $k => &$v) {
            if (!is_string($k)) {
                $kstring = false;
            }
            if (is_array($v)) {
                $this->rec_ksort($v);
            }
        }
        if ($kstring) {
            ksort($arr);
        }
        return $arr;
    }
    public function fetch($appKey, $host,  $method, $timestamp, $paramJson, $accessToken, $sign)
    {
        $methodPath = str_replace('.', '/', $method);
        $url = $host . '/' . $methodPath .
            '?method=' . urlencode($method) .
            '&app_key=' . urlencode($appKey) .

            '&timestamp=' . urlencode(strval($timestamp)) .
            '&v=' . urlencode('2') .
            '&sign_method=' . urlencode('hmac-sha256') .
            '&sign=' . urldecode($sign) .
            '&access_token=' . urlencode($accessToken);
        $opts = array(
            'http' =>
            array(
                'method' => 'POST',
                'timeout' => '120',
                'header' => "Accept: */*\r\n" .
                    "Content-type: application/json;charset=UTF-8\r\n",
                'content' => $paramJson
            )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
        // $result = $this->sendRequest($url, $paramJson);
        // 不强制处理 不然容易遗漏数据
        // if (!$result) {
        //     $result = file_get_contents($url, false, $context);
        // }
        $this->log->info('url:' . $url . '传递的参数:' . $paramJson . '返回的参数' . $result);
        return $result;
    }
    public function sendRequest($url, $data)
    {
        // var_dump($data);
        // $data  = $httpRequest->body;
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        //设置http超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, 5000);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2000);
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            // var_dump(curl_error($curl), 1111111111);
            return false;
        }
        curl_close($curl);

        return $output;
    }
    public function send($method, $data)
    {
        $paramJson = $this->marshal($data);
        $timestamp = time();
        // $timestamp = date('Y-m-d H:i:s');
        $appKey = $this->app_key; //'7052986961300030983';
        $appSecret = $this->app_secret; //'0f4b66d9-b51b-496d-b13f-03fad8a373e6';
        if ($method == 'token.create' || $method == 'token.refresh') {

            $accessToken = '';
        } else {
            $accessToken = $this->getAcToken();
        }
        if (isset($accessToken) && $accessToken === false) {
            return json_encode(['code' => 103, 'msg' => '未获取到token']);
        }

        $host = 'https://openapi-fxg.jinritemai.com';
        // 计算签名
        $signVal = $this->sign($appKey, $appSecret, $method, $timestamp, $paramJson);
        // 发起请求
        $responseVal = $this->fetch($appKey, $host, $method, $timestamp, $paramJson, $accessToken, $signVal);
        return $responseVal;
    }
}
